import { onUnmounted, onMounted, onDeactivated, ref } from "vue";
import {throttle} from "underscore"
// 监听window窗口的滚动 到底
// 当离开页面的时候移除监听

// 第一种方式
// export default function useScroll(reachBottomCB) {
//   const scrollListennerHandler = () => {
//     const clientHeight = document.documentElement.clientHeight;
//     const scollTop = document.documentElement.scrollTop;
//     const scrollHeight = document.documentElement.scrollHeight;
//     if(clientHeight+scollTop>= scrollHeight){
//        if(reachBottomCB) reachBottomCB()
//     }
//   };
//   onMounted(() => {
//     window.addEventListener("scroll", scrollListennerHandler);
//   });

//   onUnmounted(() => {
//     window.removeEventListener("scroll", scrollListennerHandler);
//   });
// }
//第二种方式
export default function useScroll() {
    const isReachBottom = ref(false);
    const scrollTop = ref(0)
    const scrollHeight = ref(0)
    const clientHeight = ref(0)
    const scrollListennerHandler = throttle(() => {
        clientHeight.value = document.documentElement.clientHeight;
        scrollTop.value = document.documentElement.scrollTop;
        scrollHeight.value = document.documentElement.scrollHeight;
        console.log("监听滚动");
        if(clientHeight.value+scrollTop.value>= scrollHeight.value){
          console.log("到达底部");
          isReachBottom.value = true
        }
      },500)
    onMounted(() => {
      window.addEventListener("scroll", scrollListennerHandler);
    });
  
    onUnmounted(() => {
      window.removeEventListener("scroll", scrollListennerHandler);
    });
    return  {isReachBottom,scrollTop,scrollHeight,clientHeight}
  } 